#!/usr/bin/env python
# encoding: utf-8
"""
@Author : Kylin
@Email : dongsai0520@gmail.com
@Time : 2022/12/14 12:38 
@Version : v1.0.0
@Remark : ***
"""

import random
import time
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from time import sleep
from selenium.webdriver import ActionChains
import yaml
import os

import xlrd
import math


def get_desired_caps(devices_name):
    """
    从yaml读取desired_caps配置信息
    参数name:设备名称,如：夜神/真机1
    :return: desired_caps字典格式

    """
    # curpath = os.path.dirname(os.path.realpath(__file__))
    yamlpath = os.path.join("./", "yaml_appium.yaml")
    # print("配置地址：%s" % yamlpath)
    f = open(yamlpath, "r", encoding="utf-8")
    a = f.read()
    f.close()
    # 把yaml文件转字典
    d = yaml.safe_load(a)
    for ii in d:
        if devices_name in ii["desc"]:  # 判断输入的设备名称是否存在
            # print(ii)
            # 启动服务
            devicesname = ii['desired_caps']['udid']
            print("devicesName: %s" % devicesname)
            # print("port: %s" %ii[\'port\'])
            # start_appium(port=ii['port'], bootstrap=ii['bootstrap-port'], udid=ii['desired_caps']['udid'])
            #start_appium(port=ii['port'], bootstrap=ii['bootstrap-port'], udid=ii['desired_caps']['udid'])
            # start_appium(port=ii[\'port\'], udid=devicesName)
            # package_name = get_package_name()
            # ii['desired_caps']['appPackage'] = package_name
            return ii['desired_caps'], ii['port']


#开启宝箱
def open_box(driver):
    print("开启宝箱")

    #三道杠菜单 延迟3s
    #26x48  => 78x144
    driver.tap([(78, 144)], 50)
    print("点击三道杠菜单")
    time.sleep(random.randint(3, 5))

    #任务中心 延迟5s
    #230x160  => 690x480
    driver.tap([(690, 480)], 50)
    print("点击任务中心")
    time.sleep(random.randint(5, 8))


    #宝箱  延迟2s
    #325x700  =>  975x2100
    driver.tap([(975, 2100)], 50)
    print("点击宝箱")
    time.sleep(random.randint(2, 4))

    #观看广告
    #5m  10m  20m  20m...
    #180x475  =>540x1425
    driver.tap([(540, 1425)], 50)
    print("点击观看广告")
    time.sleep(random.randint(35, 38))

    #35s后关闭广告
    #90x58  =>270x174
    driver.tap([(270, 174)], 50)
    print("点击关闭广告")
    time.sleep(random.randint(2, 5))

    #返回
    #24x50  =>72x150
    driver.tap([(72, 150)], 50)
    print("点击返回")


#开启自动化
def auto_appium(driver, deviceName, appPackage, appActivity):
    # global isOpenRedPackage
    # if isOpenRedPackage is False:
    #     #先展开红包
    #     #30x190  => 90x570
    #     driver.tap([(90, 570)], 50)
    #     print("展开红包")
    #     isOpenRedPackage = True
    #     time.sleep(3)

    # open_box(driver)
    #看视频总时间 单位:分钟
    dt_total = 0
    #打开宝箱的次数
    box_count = 0
    while True:

        cur_activity = driver.current_activity
        print("当前activity1:", driver.current_package + " " + cur_activity)
        #################################################################
        # com.bytedance.sdk.openadsdk.activity.TTRewardExpressVideoActivity
        if cur_activity != "com.yxcorp.gifshow.HomeActivity":
            print("偏离了activity,退回游戏内activity")
            driver.start_activity(appPackage, appActivity)
            time.sleep(3)
            dt_total = 0
            print("总观看时间清零")

        dt = random.randint(8,15)
        print(f'观看{dt}秒切换下一个视频')
        time.sleep(dt)

        dt_total = dt_total + dt
        dt_total_m = math.floor(dt_total/60)
        print(f'=========================观看总时间:{dt_total}秒')
        # print(f'=========================观看总时间:{dt_total_m}分钟')



        # if dt_total > random.randint(100,130):
        #     print("重置刷视频")
        #     driver.quit()
        #     start()
        # else:
        #     # 根据手机分辨率修改点
        #     # 200x500  => 600x1500
        #     driver.swipe(start_x=600, start_y=1500, end_x=600, end_y=1000, duration=200)
        #     print("切换下一个视频")
        #     # driver.quit()

        driver.swipe(start_x=600, start_y=1500, end_x=600, end_y=1000, duration=200)
        print("切换下一个视频")


def run_app(deviceName):
    # 配置参数
    desired_caps = get_desired_caps(deviceName)

    if desired_caps is None:
        return

    # print(desired_caps)

    appPackage = desired_caps[0]['appPackage']

    appActivity = desired_caps[0]['appActivity']

    print(appPackage)
    print(appActivity)

    #adb shell am force-stop com.sohu.sohuvideo
    # os.system(f"adb -s {deviceName} shell am force-stop {appPackage}")
    # print(f"结束app成功{appPackage}")

    # 连接Appium Server，初始化自动化环境
    driver = webdriver.Remote(f'http://localhost:{desired_caps[1]}/wd/hub', desired_caps[0])
    # time.sleep(5)

    # 每个操作的等待时间
    driver.implicitly_wait(5)

    print("run app")

    time.sleep(10)

    # run_new_guide(driver)
    auto_appium(driver, desired_caps[0]['deviceName'], desired_caps[0]['appPackage'], desired_caps[0]['appActivity'])
    # relogin_vpn_node(driver)
    # change_gaid(driver)

    #driver.quit()

def start():
    print("开始刷视频")
    run_app("b62090bf")


if __name__ == '__main__':
    # isOpenRedPackage = False
    start()